package com.cloud.logger.zchain.zchainserver.mail.impl;

import com.cloud.logger.zchain.core.common.base.ResultMessage;
import com.cloud.logger.zchain.core.common.constant.ResultCodeConstant;
import com.cloud.logger.zchain.zchainserver.entity.MailFailure;
import com.cloud.logger.zchain.zchainserver.mail.MailFailureService;
import com.cloud.logger.zchain.zchainserver.mail.util.MailSendUtil;
import com.cloud.logger.zchain.zchainserver.mongo.MailFailureRepository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 浙江卓锐科技股份有限公司
 *
 * @author zhengyt
 * @create 2017/11/15
 * @description
 */
@Service
public class MailFailureServiceImpl implements MailFailureService {

    @Resource
    MailFailureRepository mailFailureMapper;


    @Override
    public ResultMessage<MailFailure> save(MailFailure mailFailure) {
        ResultMessage resultMessage = new ResultMessage();
        mailFailure = mailFailureMapper.save(mailFailure);
        if (mailFailure.getId() != null) {
            resultMessage.setCode(ResultCodeConstant.SERVICE_SUCCESS_CODE);
            resultMessage.setId(mailFailure.getId() + "");
        } else {
            resultMessage.setCode(ResultCodeConstant.SERVICE_ERROR_CODE);
        }
        return resultMessage;
    }


    @Override
    public void sendFailureMail() {
        List<MailFailure> list = mailFailureMapper.findAll();
        ExecutorService executor = Executors.newFixedThreadPool(3);

        for (MailFailure mailFailure : list) {
            CompletableFuture.runAsync(() -> {
                try {
                    SendMail(mailFailure.getAddress(), mailFailure.getContent(), mailFailure.getContent(), mailFailure.getId());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }, executor);
        }

    }


    void SendMail(String address, String title, String content, String id) {
        try {
            MailSendUtil.sendMail(address, title, content);
            System.out.println(" 邮件发送成功.. ");
            mailFailureMapper.delete(id);
        } catch (Exception e) {
            System.out.println(" 发送失败 ");
            System.out.println(e.getLocalizedMessage());
        }
    }
}